package br.unicamp.ic.lis.docseaservice.resource;

import java.util.List;

import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.apache.log4j.Logger;
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;

import br.unicamp.ic.lis.docseaservice.model.dao.LocationUriDAO;
import br.unicamp.ic.lis.docseaservice.model.vo.LocationUri;
import br.unicamp.ic.lis.docseaservice.response.LocationUriResponse;

import com.vividsolutions.jts.geom.Polygon;
import com.vividsolutions.jts.io.ParseException;
import com.vividsolutions.jts.io.WKTReader;

@Path("/query")
public class QueryResource {
	private static Logger LOG = Logger.getLogger(QueryResource.class);
	private static final int SRID = 4326;

	@POST
	@Produces(MediaType.APPLICATION_JSON)
	@Consumes(MediaType.TEXT_PLAIN)
	public Response get(String message) {
		LOG.info("Query received: " + message);

		Polygon p = null;
		try {
			p = (Polygon) new WKTReader().read(message);
		} catch (ParseException e) {
			LOG.error("Bad parameter");
			throw new WebApplicationException(400);
		}
		if (p == null) {
			LOG.error("Failed to get polygon");
			throw new WebApplicationException(400);
		}

		p.setSRID(SRID);
		LocationUriDAO dao = new LocationUriDAO();
		List<LocationUri> result = dao.get(p);

		JSONArray jsonArray = new JSONArray();
		for (int i = 0; i < result.size(); i++) {
			LocationUriResponse response = new LocationUriResponse(
					result.get(i));
			JSONObject jsonObject = new JSONObject();
			try {
				jsonObject.put("uri", response.getUri());
				jsonObject.put("country", response.getCountry());
				jsonObject.put("state", response.getState());
				jsonObject.put("city", response.getCity());
				jsonObject.put("latitude", response.getLatitude());
				jsonObject.put("longitude", response.getLongitude());
			} catch (JSONException e) {
				LOG.error("Fatal error: ", e);
				throw new WebApplicationException(500);
			}
			jsonArray.put(jsonObject);
		}
		String finalResult = jsonArray.toString();
		LOG.info("Result: " + finalResult);
		return Response.ok(finalResult).build();
	}

}
